import smtplib
from email.mime.text import MIMEText
from django.conf import settings
#设置服务器所需信息
#163邮箱服务器地址
mail_host = settings.MAILHOST
#163用户名
mail_user = settings.MAILUSER
#密码(部分邮箱为授权码)
mail_pass = settings.MAILPASSWORD
#邮件发送方邮箱地址
sender = settings.MAILSENDER


def send_email(email, title, code):
    # 设置email信息
    # 邮件内容设置
    message = MIMEText(f'你的验证码为: {code}', 'plain', 'utf-8')
    # 邮件主题
    message['Subject'] = title
    # 发送方信息
    message['From'] = sender
    # 接受方信息
    message['To'] = email

    receivers = [email, ]

    #登录并发送邮件
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host)
        #登录到服务器
        smtpObj.login(mail_user,mail_pass)
        #发送
        smtpObj.sendmail(
            sender,receivers,message.as_string()
        )
        #退出
        smtpObj.quit()
        response = {'result': 0}
    except smtplib.SMTPException as e:
        response = {'result': 1000, 'errmsg': "网络异常发送失败"}

    return response
